package com.acane.instagram.feature.profile

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.feature.common.SessionManager
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

class ProfileViewModel(
    savedStateHandle: SavedStateHandle
): ViewModel() {
    private val userId: String = checkNotNull(savedStateHandle[PROFILE_ROUTE_WITH_USER_ID])
    var currentUserInfo by mutableStateOf<UserInfo?>(null)

    private var _refresh = MutableStateFlow<Boolean>(false)
    val refresh = _refresh

    fun startRefresh() {
        viewModelScope.launch {
            _refresh.value = true
            delay(1000)
            _refresh.value = false
            loadInitialData()
        }
    }

    private val _isFollowed = MutableStateFlow<Boolean>(false)
    val isFollowed: MutableStateFlow<Boolean> = _isFollowed
    // 更新isFollowed的值
    fun updateIsFollowed(newValue: Boolean) {
        _isFollowed.value = newValue
        // 更新数据库
        if (newValue) {
            viewModelScope.launch {
                followerId?.let { MyRetrofitDatasource.sendFollowRequest(followingId, it) }
            }
        } else {
            viewModelScope.launch {
                followerId?.let { MyRetrofitDatasource.sendUnFollowRequest(followingId, it) }
            }
        }
    }
    val followingId = userId
    val followerId = SessionManager.currentUser?.id
    private val _postDatum = MutableStateFlow<List<PostInfo>>(emptyList())
    val postDatum: MutableStateFlow<List<PostInfo>> = _postDatum
    private val _gridPostData = MutableStateFlow<List<PostInfo>>(emptyList())
    val gridPostData: MutableStateFlow<List<PostInfo>> = _gridPostData
    private val _videoPostData = MutableStateFlow<List<PostInfo>>(emptyList())
    val videoPostData: MutableStateFlow<List<PostInfo>> = _videoPostData

    val gridBoxInfo: MutableStateFlow<Map<PostInfo, String>> = MutableStateFlow(emptyMap())
    init {
        loadInitialData()
    }
    private fun loadInitialData() {
        viewModelScope.launch {
            // 步骤 1：先获取主数据
            loadPostData().join() // 等待数据加载完成

            // 步骤 2：处理后续过滤
            loadGridPostData()
        }
        viewModelScope.launch {
            Log.d(TAG, "开始初始化当前页面用户数据")
            currentUserInfo = MyRetrofitDatasource.getUserById(userId).data!!
            Log.d(TAG, "loadUserData: $currentUserInfo")
        }
        viewModelScope.launch {
            isFollowed.value = MyRetrofitDatasource.judgeIsFollowed(followingId, followerId).data!!
        }
    }

    fun loadGridPostData() {
        val gridPosts = mutableListOf<PostInfo>()
        val videoPosts = mutableListOf<PostInfo>()

        postDatum.value.forEach { post ->
            when (post.showRange) {
                "grid_and_reels" -> {
                    if (post.urls.size == 1 && post.urls.first().endsWith(".mp4")) {
                        videoPosts.add(post)
                    }
                    gridPosts.add(post)
                }
                "reels" -> {
                    videoPosts.add(post)
                }
            }
        }

        _gridPostData.value = gridPosts
        _videoPostData.value = videoPosts

        _gridPostData.value.forEach { post ->
            val uris = post.urls
            if (uris.size > 1) {
                gridBoxInfo.value = gridBoxInfo.value + (post to "isGrid")

            } else if (uris.size == 1 && uris.first().endsWith(".mp4")) {

                gridBoxInfo.value = gridBoxInfo.value + (post to "isVideo")
            }
        }
    }

    // 修改为返回 Job 用于同步
    private fun loadPostData(): Job = viewModelScope.launch {
        Log.d("MeViewModel", "开始初始化数据")
        val newData = userId.let {
            try {
                MyRetrofitDatasource.getPostListById(it).data
            } catch (e: Exception) {
                Log.e("MeViewModel", "网络请求失败", e)
                emptyList<PostInfo>()
            }
        } ?: emptyList()
        _postDatum.value = newData
    }


    companion object {
        const val TAG = "ProfileViewModel"
    }
}